﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DemoMedia.Models;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace DemoMedia.ViewModels
{
	public class MainWindowViewModel : ObservableObject
	{
        private MainWindowM model;

        public MainWindowM Model
        {
            get { return model; }
            set { SetProperty(ref model , value); }
        }


        private MediaElement media;

        private Task mediaTask;

        private bool IsRunning=false;

		public MainWindowViewModel()
		{
            Model=new MainWindowM()
            {
                Movies = new ObservableCollection<Movie>()
            };
			
		}

        #region Loaded

        private RelayCommand<object> loadedCommand;

        public RelayCommand<object> LoadedCommand
        {
            get
            {
                if (loadedCommand == null)
                {
                    loadedCommand = new RelayCommand<object>(Loaded);
                }
                return loadedCommand;
            }
        }

		private void Loaded(object obj)
		{
			var args = obj as RoutedEventArgs;
			if (args != null)
			{
				var win= args.OriginalSource as MainWindow;
				this.media = win.mediaElement;
			}
        }

        #endregion

        #region 浏览视频

        private RelayCommand browserCommand;

		public RelayCommand BrowserCommand
		{
			get
			{
				if (browserCommand == null)
				{
					browserCommand = new RelayCommand(Browser);
				}
				return browserCommand;
			}
		}

		private void Browser()
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.Title = "请选择要播放的影片";
			dialog.Filter = "MP4|*.mp4";
			dialog.Multiselect = true;
			if (dialog.ShowDialog()==true)
			{
				var files=dialog.FileNames;
				foreach (var file in files)
				{
					var maxId = this.Model.Movies.Count>0 ? this.Model.Movies.Max(x => x.Id):0;
					if (this.Model.Movies.FirstOrDefault(item => item.Url == file) == null)
					{
						this.Model.Movies.Add(new Movie()
						{
							Id = maxId + 1,
							Name = Path.GetFileNameWithoutExtension(file),
							Url = file
						});
					}
				}
			}
		}

        #endregion

        #region 双击列表打开视频


        private RelayCommand<object> mouseDoubleCommand;

		public RelayCommand<object> MouseDoubleCommand
		{
			get
			{
				if(mouseDoubleCommand == null)
				{
					mouseDoubleCommand = new RelayCommand<object>(MouseDoubleClick);
				}
				return mouseDoubleCommand;
			}
		}

		private void MouseDoubleClick(object obj)
		{
			if (obj == null)
			{
				return;
			}
			this.Model.CurMovie = obj as Movie;
            this.Play();
		}

        #endregion

        #region 视频操作

        private RelayCommand playCommand;

        public RelayCommand PlayCommand
        {
            get
            {
                if (playCommand == null)
                {
                    playCommand = new RelayCommand(Play);
                }
                return playCommand;
            }
        }

        private void Play()
        {
            //影片播放，如果没有，则打开选择文件夹
            if (this.Model.CurMovie == null)
            {
                this.Browser();
                if (this.Model.Movies.Count < 1)
                {
                    return;
                }
                this.Model.CurMovie = this.Model.Movies.Last();
            }
            this.Model.CurSource = new Uri(this.Model.CurMovie.Url, UriKind.RelativeOrAbsolute);
            if (this.media.NaturalDuration != Duration.Automatic && this.media.Position.TotalSeconds == this.media.NaturalDuration.TimeSpan.TotalSeconds)
            {
                this.media.Position=new TimeSpan(0,0,0);
            }
            this.media.Play();
            this.IsRunning = true;
            this.Model.PlayButtonVisibility = Visibility.Collapsed;
            //
            this.mediaTask = Task.Run(() =>
            {
                while (this.IsRunning)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        this.Model.Position = this.media.Position.TotalSeconds;
                    });
                    Thread.Sleep(100);
                }
            });
        }


        private RelayCommand pauseCommand;

        public RelayCommand PauseCommand
        {
            get
            {
                if (pauseCommand == null)
                {
                    pauseCommand = new RelayCommand(Pause);
                }
                return pauseCommand;
            }
        }

        private void Pause()
        {
            if (this.Model.CurMovie == null)
            {
                return;
            }
            this.media.Pause();
            this.IsRunning = false;
        }

        private RelayCommand stopCommand;

        public RelayCommand StopCommand
        {
            get
            {
                if (stopCommand == null)
                {
                    stopCommand = new RelayCommand(Stop);
                }
                return stopCommand;
            }
        }

        private void Stop()
        {
            if (this.Model.CurMovie == null)
            {
                return;
            }
            this.media.Stop();
            this.IsRunning= false;
        }


        private RelayCommand mediaOpenedCommand;

        public RelayCommand MediaOpenedCommand
        {
            get
            {
                if (mediaOpenedCommand == null)
                {
                    mediaOpenedCommand = new RelayCommand(MediaOpened);
                }
                return mediaOpenedCommand;
            }
        }

        private void MediaOpened()
        {
            if (this.media.NaturalDuration.TimeSpan.TotalMinutes < 60)
            {
                this.Model.TimeLen = this.media.NaturalDuration.TimeSpan.ToString(@"mm\:ss");
            }
            else
            {
                this.Model.TimeLen = this.media.NaturalDuration.TimeSpan.ToString(@"hh\:mm\:ss");
            }
            this.Model.MediaMaximum = this.media.NaturalDuration.TimeSpan.TotalSeconds;
        }

        private RelayCommand mediaEndedCommand;

        public RelayCommand MediaEndedCommand
        {
            get
            {
                if (mediaEndedCommand == null)
                {
                    mediaEndedCommand = new RelayCommand(MediaEnded);
                }
                return mediaEndedCommand;
            }
        }

        private void MediaEnded()
        {
            this.Model.PlayButtonVisibility = Visibility.Visible;
            this.IsRunning = false;
        }
        #endregion
    }
}
